extends Node

@export var mob_scene: PackedScene
var score

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	#new_game()
	pass


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	pass


func game_over() -> void:
	$ScoreTimer.stop()
	$MobTimer.stop()
	$HUD.show_game_over()


func new_game():
	score = 0
	$Player.start($StartPosition.position)
	$StartTimer.start()
	$HUD.update_score(score)
	$HUD.show_message("Get Ready")
	# get_tree() 获取当前场景树
	# call_group("mobs", "queue_free") 调用所有属于 "mobs" 组的节点的 queue_free() 方法
	# queue_free() 是 Godot 中安全删除节点的方法，会在当前帧结束后删除节点
	# 这确保新游戏开始时，场上不会残留上一局的敌人
	'''
	queue_free() 是 Godot 引擎的内置方法，属于 Node 类。它的作用是：

	安全删除节点：将节点标记为待删除，但不会立即删除
	延迟删除：节点会在当前帧处理完毕后被删除
	避免崩溃：防止在节点正在处理逻辑时被删除导致的错误
	'''
	get_tree().call_group("mobs", "queue_free")


func _on_start_timer_timeout() -> void:
	$MobTimer.start()
	$ScoreTimer.start()


func _on_score_timer_timeout() -> void:
	score += 1
	$HUD.update_score(score)


func _on_mob_timer_timeout() -> void:
	var mob = mob_scene.instantiate()
	var mob_spawn_location = $MobPath/MobSpawnLocation
	mob_spawn_location.progress_ratio = randf() #

	mob.position = mob_spawn_location.position

	var direction = mob_spawn_location.rotation + PI / 2

	direction += randf_range(-PI / 4, PI / 4)
	mob.rotation = direction

	var velocity = Vector2(randf_range(150.0, 250.0), 0.0)
	mob.linear_velocity = velocity.rotated(direction)

	add_child(mob)
